"""Testing MorseSender.

To perform all tests:
    edit test_instantiation() to use the boards' IP-adress
    python3 -m pytest
To get coverage  (needs pytest-cov plugin)
    python3 -m pytest --cov=morsesender --cov-report annotate --cov-report term

Most MorseSender methods do not return anything and only exist for their side
effects. Testing primarily just calls the methods: it mainly tests for
running them without exceptions.
"""

import pytest
from morsesender import MorseSender
from utils import new_brightness, mylog
from config import Config


@pytest.fixture
def sender():
    """A fixture to set up and tear down a MorseSender object."""
    s = MorseSender(Config.ADDRESS, Config.PORT, Config.DIT)
    s._secs_dit = 0.001           # speed up for faster tests
    s._secs_dah = 0.003
    s._secs_letter_sep = 0.003
    s._secs_word_sep = 0.007
    yield s
    s.shutdown()


def test_instantiation(sender):
    assert isinstance(sender, MorseSender)
    assert sender._address == Config.ADDRESS


def test_brightness(sender, capsys):
    sender.sendmsg(1, "T")
    assert capsys.readouterr().err == ""
    sender.sendmsg(6, "T")
    assert capsys.readouterr().err == ""


def test_sendmsg(sender, capsys):
    sender.sendmsg(new_brightness(), "TE K20")
    assert capsys.readouterr().out == "- .       -.- ..--- -----\n"


def test_inter_message(sender, capsys):
    sender.inter_message(new_brightness(), 2)
    assert capsys.readouterr().out == "\n" + ("z" * 72) + "\n"


def test_shutdown(caplog):
    # Not using the sender fixture to prevent double shutdown() call.
    caplog.set_level(mylog.INFO)
    s = MorseSender(Config.ADDRESS, Config.PORT, Config.DIT)
    s.shutdown()
    assert "board shut down" in caplog.text
